package com.woniu.interceptor;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.woniu.utils.JWTUtil;
import com.woniu.utils.ResponseEnum;
import com.woniu.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplateInit;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if (token == null){
            log.error("token为空 验证失效");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
            return false;
        }
//        log.info("用户已登录");
        try {
            boolean flag = JWTUtil.verifyToken(token);
            if (!flag) {
                log.error("token 不合法");
                response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("token 不合法");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
            return false;
        }
        Map payload = JWTUtil.getPayload(token);
        Object userId = payload.get("id");
        String redisToken =(String) redisTemplateInit.opsForValue().get("jwt:loginUser:"+userId);
        if (!token.equals(redisToken)) {
            log.error("token过期");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
            return  false;
        }
        redisTemplateInit.opsForValue().set("jwt:loginUser:"+userId,token,60, TimeUnit.MINUTES);
        redisTemplateInit.expire("bookDetail", 30+ RandomUtil.randomInt(10), TimeUnit.MINUTES);

        return true;
    }
}
